package appli.calcul;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class Recherche extends Activity{

	private Spinner zone;
	private Spinner cat;
	private EditText nom;
	private EditText addr;
	private Button valider;
	private static final int MON_CODE = 1;
	private DatabaseAdaptateur mabd;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.recherche);

		zone = (Spinner) findViewById(R.id.zone);
		cat = (Spinner) findViewById(R.id.categorie);
		nom = (EditText) findViewById(R.id.nombat);
		addr = (EditText) findViewById(R.id.addr);
		valider = (Button) findViewById(R.id.btrecherche);
		this.mabd = new DatabaseAdaptateur(getApplicationContext());

		mabd.open();
		
		
		ArrayAdapter<?> adapterz = ArrayAdapter.createFromResource(this, R.array.zone, android.R.layout.simple_spinner_item);
		adapterz.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		zone.setAdapter(adapterz);

		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.categorie, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		cat.setAdapter(adapter);

		final boolean iti = getIntent().getExtras().getBoolean("iti");
		//créer le listener du bouton recherche 

		final Activity act = this;


		valider.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if(iti)
				{
					Intent recherche = new Intent();
					recherche.putExtra("iti", iti);
					recherche.putExtra("addr", addr.getText().toString());
					recherche.putExtra("nom", nom.getText().toString());
					recherche.putExtra("zone", zone.getSelectedItem().toString());
					recherche.putExtra("cat", cat.getSelectedItem().toString());
					setResult(RESULT_OK, recherche);
					finish();
				}
				else
				{
					Intent recherche = new Intent(act, Resultat.class);
					recherche.putExtra("iti", iti);
					recherche.putExtra("nom", nom.getText().toString());
					act.startActivityForResult(recherche, MON_CODE);
				}
			}
		});


	}
	
	protected void onActivityResult(int ident, int code_retour, Intent retour)
	{
		switch(ident)
		{
			case MON_CODE : 
				Intent ret = new Intent();
				ret.putExtra("id", retour.getExtras().getInt("id"));
				ret.putExtra("lat", retour.getExtras().getDouble("lat"));
				ret.putExtra("lon", retour.getExtras().getDouble("lon"));
				setResult(RESULT_OK, ret);
				finish();
				return;

		}
	}	
}
